package org.xue.snowmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.xue.snowmall.common.utils.PageUtils;
import org.xue.snowmall.common.utils.Query;

import org.xue.snowmall.search.config.SnowMallEsConfig;
import org.xue.snowmall.search.dao.GoodsDao;
import org.xue.snowmall.search.entity.GoodsEntity;
import org.xue.snowmall.search.service.GoodsService;
import org.xue.snowmall.search.vo.SearchVo;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {

    @Autowired
    private RestHighLevelClient client;
    @Override
    public PageUtils<GoodsEntity> queryPage(Map<String, Object> params) {
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<GoodsEntity>()
        );

        return new PageUtils<>(page);
    }

    @Override
    public PageUtils<GoodsEntity> esList(SearchVo vo, Integer page, Integer limit) throws IOException {

        //es查询所有商品
        SearchRequest searchRequest = new SearchRequest("snow-goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.size(limit);
        searchSourceBuilder.from((page - 1) * limit);

        searchRequest.source(searchSourceBuilder);

        SearchResponse search = client.search(searchRequest, SnowMallEsConfig.COMMON_OPTIONS);

        Long value = search.getHits().getTotalHits().value;
        List<GoodsEntity> list = new ArrayList<>();
        for (SearchHit hit : search.getHits().getHits()) {
            GoodsEntity goodsEntity = JSON.parseObject(hit.getSourceAsString(), GoodsEntity.class);
            list.add(goodsEntity);
        }


        return new PageUtils<>(list,value.intValue(),limit,page);
    }

}